package handler

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"takeout_server/basic/dao"
	Gs "takeout_server/basic/proto/good"
)

type GoodServer struct {
	Gs.UnimplementedGoodServerServer
}

func (s *GoodServer) GoodAdd(_ context.Context, req *Gs.GoodAddReq) (*Gs.GoodAddResp, error) {

	goodadd, err := dao.GoodAdd(req.Name, float64(req.Price), req.Img, int64(req.SalesVolume), uint32(req.GoodType))
	if err != nil {
		return nil, err
	}

	//fmt.Println(good)
	if goodadd.Id == 0 {
		zap.L().Info("商品添加失败失败")
		return nil, errors.New("商品添加失败")
	}
	//fmt.Println(good)
	return &Gs.GoodAddResp{GoodId: int32(goodadd.Id)}, nil
}

func (s *GoodServer) GoodWhere(_ context.Context, req *Gs.GoodWhereReq) (*Gs.GoodWhereResp, error) {

	goodlist, err := dao.GoodWheres()
	if err != nil {
		zap.L().Info("商品展示失败")
		return nil, err
	}

	goodList := []*Gs.GoodList{}
	for _, good := range goodlist {
		goodList = append(goodList, &Gs.GoodList{
			Name:        good.Name,
			Price:       float32(good.Price),
			Img:         good.Img,
			SalesVolume: uint64(good.SalesVolume),
			GoodType:    int32(good.GoodType),
		})
	}
	return &Gs.GoodWhereResp{List: goodList}, nil
}
